package com.ddwl.goods.service.bargain;

import cn.hutool.core.util.StrUtil;
import com.ddwl.common.constant.BaseEnum;
import com.ddwl.common.exception.ParamException;
import com.ddwl.common.feign.api.ShopApi;
import com.ddwl.common.util.BeanConverUtils;
import com.ddwl.goods.dao.bargain.BargainConfigDao;
import com.ddwl.goods.model.bargain.BargainConfig;
import com.ddwl.schema.bo.goods.bargain.BargainConfigAddBo;
import com.ddwl.schema.vo.goods.bargain.BargainConfigVo;
import com.ddwl.schema.vo.shop.ShopVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;

/**
 * @Author hemiaojun
 * @Date 2020/11/6 13:51
 */
@Service
public class BargainConfigService {

    @Resource
    private BargainConfigDao bargainConfigDao;
    @Resource
    private ShopApi shopApi;

    public void save(BargainConfigAddBo bo) {
        if (StrUtil.isEmpty(bo.getShopId())) {
            ShopVo shopVo = shopApi.getDefaultShopForApi().getResult();
            ParamException.isNull(shopVo, "店铺信息不存在");
            bo.setShopId(shopVo.getId());
        }
        BargainConfig entity = BeanConverUtils.convertBean(bo, BargainConfig.class);
        BargainConfig exist = get(bo.getShopId());
        if (null != exist) {
            entity.setId(exist.getId());
            entity.setGmtCreated(exist.getGmtCreated());
            entity.setGmtModified(Instant.now());
            entity.setDflag(BaseEnum.DflagEnum.NOT_DELETE.getCode());
            entity.setEnable(BaseEnum.StatusEnum.ENABLE.getCode());
            bargainConfigDao.update(entity);
        }else{
            entity.setEnable(BaseEnum.StatusEnum.ENABLE.getCode());
            bargainConfigDao.insert(entity);
        }

    }

    private BargainConfig get(String shopId){
        BargainConfig entity = new BargainConfig();
        entity.setShopId(shopId);
        entity.setEnable(BaseEnum.StatusEnum.ENABLE.getCode());
        return bargainConfigDao.selectOne(entity);
    }

    public BargainConfigVo getBargainConfig(String shopId) {
        if (StrUtil.isEmpty(shopId)) {
            ShopVo shopVo = shopApi.getDefaultShopForApi().getResult();
            ParamException.isNull(shopVo, "店铺信息不存在");
            shopId = shopVo.getId();
        }
        return BeanConverUtils.convertBean(get(shopId),BargainConfigVo.class);
    }
}
